<template>

</template>

<script>
	import {mapGetters,mapState} from 'vuex';
	export default {
		data() {
			return {
				code: '', // 微信返回 code
			};
		},
		computed: {
			...mapState({
				oldCode: 'oldCode'
			})
		},
		created() {
			// 获取地址参数
			console.log(location.search,'location.search')
			const params = new URLSearchParams(location.search);
			this.code = params.get('code');
			console.log(this.code,'code')
			console.log(this.oldCode,'旧的code')
			if(!this.code){
				this.init()
			}else{
				if(this.oldCode==this.code){
					return this.init()
				}
				this.$store.commit("updateCode",this.code);
				this.login()
			}
		},
		methods: {
			init() {
				var url='https://guahao.tcyy.org.cn/#/login'
				// var url='https://guahao.tcyy.org.cn'  //测试--去掉 
				// let local = encodeURI(url); //获取当前页面地址作为回调地址
				// var url=window.location.href
				let local = encodeURIComponent(url); //获取当前页面地址作为回调地址
				let appid = 'wx7cbe187d6eb21122'
				//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				window.location.href =
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
					appid + 
					"&redirect_uri=" +
					local + 
					"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			},
			login() {
				// 发送请求,用post方式
				let url = "/api/index";
				this.$axios.get(url,{
					params:{
						code:this.code
					}
				}).then(res => {
					console.log(res,'用户信息')
					// 修改登陆状态
					this.$store.commit("updateLogin", true);
					// 把token存入store
					this.$store.commit("updateToken", res.ack_info.Authorization);
					this.$router.push("/index");
				}).catch(err => {
					console.log('登陆失败')
				});
			}
			
			
		}
	};
</script>

<style lang="less" scoped>
	@import "./login.less";

	.logo {
		font-size: 100px !important;
		margin-bottom: 150px;
	}
</style>